package com.oauth.extensions.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.DeckPanel;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.oauth.auth.client.beans.MemberClientBean;
import com.oauth.auth.client.rpc.MemberRemoteService;
import com.oauth.auth.client.rpc.MemberRemoteServiceAsync;
import com.oauth.components.client.rpc.OAuthAsnyCallBack;
import com.oauth.components.client.rpc.exception.SessionExpiredException;
import com.oauth.extensions.client.ui.LoginPanel;
import com.oauth.global.client.rpc.GlobalRemoteService;
import com.oauth.global.client.rpc.GlobalRemoteServiceAsync;
import com.oauth.global.client.ui.BirthdayNotification;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class BirthdayExtensionEntryPoint implements EntryPoint {

	private final MemberRemoteServiceAsync memberService = GWT.create(MemberRemoteService.class);

	private final GlobalRemoteServiceAsync globalService = GWT.create(GlobalRemoteService.class);

	private static ExtensionEntryPointUiBinder uiBinder = GWT
			.create(ExtensionEntryPointUiBinder.class);

	interface ExtensionEntryPointUiBinder extends UiBinder<DockLayoutPanel, BirthdayExtensionEntryPoint> {
	}

	@UiField
	LoginPanel loginPanel;

	@UiField
	DeckPanel deckPanel;

	@UiField
	BirthdayNotification birthdayNotification;

	public void onModuleLoad() {
		DockLayoutPanel p = uiBinder.createAndBindUi(this);

		deckPanel.showWidget(0); // show loading image.
		memberService.getMember(new OAuthAsnyCallBack<MemberClientBean>() {
			public void onSuccess(MemberClientBean result) {
				if (result == null) {
					deckPanel.showWidget(1); // shows sign in button.
				} else {
					deckPanel.showWidget(2);// show birthdays.
					birthdayNotification.setService(globalService);
					birthdayNotification.initBirthdays();
				}
			}

			public void onFailure(Throwable pCaught) {
				try {
					throw pCaught;
				} catch (SessionExpiredException e) {
					deckPanel.showWidget(1); // shows sign in button.
				} catch (Exception e) {
					Window.alert("Sorry. Something went wrong in server.Please try again");
				} catch (Throwable e) {
					Window.alert("Sorry. Something went wrong in server.Please try again");
				}
			}
		});

		RootLayoutPanel rp = RootLayoutPanel.get();
		rp.add(p);
		// RootPanel.get().add(dockPanel);
	}
}
